import { getFilesPath } from '@/utils/files'
import Router from 'koa-router'
import Koa from 'koa'
import path from 'path'
import koaBody from 'koa-body'
import koaJson from 'koa-json'

class AllRouterLoader {
  static allRouterLoader = new AllRouterLoader()
  private router!: Router
  private app!: Koa

  /**
   * 初始化路由相关
   *
   * @param app Koa实例
   * @param router 路由实例
   * @param prefix 所有路由的前缀，默认`/api`
   */
  async init(app: Koa, router: Router, prefix = '/api') {
    this.app = app
    this.router = router
    app.use(koaBody())
    app.use(koaJson())
    this.router.prefix(prefix)
    await this.registerRoutes()
  }

  /**
   * 获取所有路由文件
   */
  private async getRouterFiles() {
    const routerDir = path.join(process.cwd(), 'src/router')
    const routerFilePaths = (await getFilesPath(routerDir)).map((file) => path.join(routerDir, file))
    return routerFilePaths
  }

  /**
   * 根据路由文件注册路由
   */
  private async registerRoutes() {
    const routers = await this.getRouterFiles()
    for (const route of routers) {
      const routeInstance = require(route)
      if (routeInstance instanceof Router) {
        this.router.use(routeInstance.routes())
      }
    }
    this.app.use(this.router.routes())
  }
}

export default AllRouterLoader.allRouterLoader
